package com.gourd.index.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gourd
 */
@Configuration
public class DruidConfig {
 
    @Value("${druid.monitor.login.user_name}")
    private String loginUsername;
 
    @Value("${druid.monitor.login.password}")
    private String loginPassword;
 
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }
 
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.setServlet(new StatViewServlet());
        Map<String, String> initParameters = new HashMap<>(8);
        //禁用HTML页面上的“Rest All”功能
        initParameters.put("resetEnable", "false");
        //initParameters.put("allow", "10.8.9.115");  //ip白名单（没有配置或者为空，则允许所有访问）
        initParameters.put("loginUsername", StringUtils.isNotBlank(loginUsername) ? loginUsername : "root");
        //监控页面登录用户密码
        initParameters.put("loginPassword", StringUtils.isNotBlank(loginPassword) ? loginPassword : "root");
        //initParameters.put("deny", "127.0.0.1"); //ip黑名单
        //如果某个ip同时存在，deny优先于allow
        reg.setInitParameters(initParameters);
        return reg;
    }
}